#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年9月7日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

'''
    按门店导出rawdata,添加门店基本信息
'''

groupStr = '''32015522    2816    南城莞太路永赢美宜佳    1    -56    -70
32015523    G619    广东东莞东城涌翠庭美宜佳    1    -56    -70
32015524    2305    南城金福美宜佳    1    -56    -70
32015526    0628    南城新银丰美宜佳    1    -56    -70
32015527    G299    广东东莞南城广彩路美宜佳    1    -56    -70
32015528    G483    广东东莞南城三元里美宜佳    1    -56    -70
32015530    G816    广东东莞莞城光辉大厦美宜佳    1    -56    -72
32015531    0300    东城涡岭美宜佳    1    -56    -70
32015532    6039    南城亨美美宜佳    1    -56    -70
32016243    6666    南城外运大厦美宜佳    0    -56    -70'''

import logging

sys.path.append('../')
from base.time_method import myTimeMethod
from base.file_method import analyze_rawdata
from base.strChar import *

def getRoleFromHiveFile(day=None,groups = []):
    rfile = '/Udisk/new_role/%s/part-00000'%day
    #2015-08-01,32013138,d8:bb:2c:f0:60:73,2015-08-01 18:10:48,2015-08-01 18:10:48,0,1,Apple
    datas = {}
    if not os.path.exists(rfile):
        logging.error('role file %s not exists'%rfile)
        sys.exit()
    for line in open(rfile).read().split('\n'):
        pass
        lineList = line.split(',')
        if len(lineList) < 8:continue
        group = lineList[1]
        if group not in groups:continue
        mac = lineList[2]
        st = lineList[3][11:]
        et = lineList[4][11:]
        dur = lineList[5]
        role = lineList[6]
        fac = lineList[7]
        if int(role) in (3,10):
            role_name = '顾客'
        elif int(role) in (1,-1):
            role_name = '路人'
        else:
            role_name = '员工'
        if group not in datas.keys():
            datas[group] = {}
        if mac not in datas[group].keys():
            datas[group][mac] = []
            
        datas[group][mac].append({'st':st,'et':et,'dur':dur,'role':role_name,'fac':fac})
    return datas


def analysis_group_info(groupStr):
    datas = {}
    for line in groupStr.split('\n'):
        #print line
        group,serial_number,shop_name,walkby,customer_rssi,flow_rssi = line.split('    ')
        
        datas[group] = {'serial_number':serial_number,'shop_name':shop_name,'walkby':walkby,'customer_rssi':customer_rssi,'flow_rssi':flow_rssi}
    return datas

    

def get_factory():
    datas = {}
    for line in open(os.path.join(current_dir,'../base/factory.txt')).read():
        try:
            mac,fac_en,fac_ch  = line.split(',')
        except:continue
        
        datas[mac] = fac_en
    return datas

def check_mac_global_or_local(mac):
    b = hex2bin(mac[:2])
    #print mac[:2], b
    if int(b[6])==0:
        return 'global'
    else:
        return 'local'


def get_rawdata_with_group_info(st='2015-08-01',et='2015-08-31'):    
    days = myTimeMethod.get_slist_between_st_et(st, et)
    
    groupInfo = analysis_group_info(groupStr)
    facs = get_factory()
    for day in days:
        roleInfo = getRoleFromHiveFile(day=day,groups = groupInfo.keys())
        logging.info('load role file OK')
        for group , groupRole in roleInfo.iteritems():
            shop_name = groupInfo[group]['shop_name']
            serial_number = groupInfo[group]['serial_number']
            walkby = '%ss'%groupInfo[group]['walkby']
            customer_rssi = str(groupInfo[group]['customer_rssi'])
            print day,group,shop_name
            
            group_rawfile = '/Udisk/rawdata_group/%s/%s.txt.tar.gz'%(day,group)
            if not os.path.exists(group_rawfile):
                logging.error('rawdata file %s not exists.'%group_rawfile)
                
            export_file =os.path.join(current_dir, 'log/macs.details.%s.%s.txt'%(shop_name,day))
            fr = open(export_file,'w')
            fr.write('MAC地址,信号强度,出现时间,MAC出现的店铺名称,MAC出现的店铺编号,该店铺定义的入店信号强度规则,该店铺定义的入店时长规则,MAC角色判定,MAC设备类型\n')
            for day,device,mac,stime,rssi in analyze_rawdata(group_rawfile):
                if mac not in groupRole.keys():
                    logging.debug('mac %s not in role'%mac)
                    mac_role = '-'
                    mac_dur = '-'
                    fac = '-'
                else:
                    for macData in groupRole[mac]:
                        st = macData['st']
                        et = macData['et']
                        role = macData['role']
                        dur = str(int(macData['dur'])/1000)
                        fac = macData['fac']
                        #MAC地址    信号强度    出现时间    MAC出现的店铺名称    MAC出现的店铺编号    该店铺定义的入店信号强度规则    该店铺定义的入店时长规则    MAC角色判定    MAC设备类型
                        
                        if stime >= st and stime <= et:
                            mac_role = role
                            mac_dur = dur
                            break
                        else:
                            mac_role = '-'
                            mac_dur = '-'
                if fac == '-':
                    try:
                        fac = facs[mac[:8]]
                    except:
                        fac = '-'
                if fac == '-':
                    if check_mac_global_or_local(mac)=='local':
                        fac = '随机'
                data =[mac,rssi,'%s %s'%(day,stime),shop_name,serial_number,customer_rssi,walkby,mac_role,fac]
                fr.write( ','.join(data)+'\n')
                
            fr.close()    
            
if __name__ == '__main__':
    import argparse,re,datetime,time
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--st',metavar=u"starttime",default=None)
    parser.add_argument('--et',metavar="endTime",default=None)
    args = parser.parse_args()
    st = args.st
    et = args.et
    get_rawdata_with_group_info(st,et)
    
    #groupInfo = analysis_group_info(groupStr)

